<template>
  <!-- <div class="chart" :id="id" :class="className" /> -->
  <div class="chart" ref="myChartRef" :class="className" :style="cssChart" />
</template>

<script>
import * as echarts from "echarts";
export default {
  props: {
    id: {
      type: String,
      default: "chart",
    },
    border: {
      default: 1,
    },
    className: {
      type: String,
      default: "",
    },
    loading: {
      type: Boolean,
      default: false,
    },
    options: {
      type: Object,
      default: () => ({}),
      required: true,
    },
  },
  data() {
    return {
      myChart: null,
      myChartRef: null,
      cssChart: {
        "--border": this.border,
      },
    };
  },
  mounted() {
    this.initChart();
  },
  methods: {
    resizeHandler() {
      this.myChart.resize();
    },
    debounce(fun, delay) {
      let timer;
      return function () {
        if (timer) {
          clearTimeout(timer);
        }
        timer = window.setTimeout(() => {
          fun();
        }, delay);
      };
    },
    initChart() {
      this.myChart = echarts.init(this.$refs.myChartRef, null, {
        renderer: 'svg',
      });
      this.myChart.showLoading({
        text: "",
        color: "#409eff",
        textColor: "#000",
        maskColor: "rgba(255, 255, 255, .95)",
        zlevel: 0,
        lineWidth: 2,
      });

      if (!this.loading) {
        this.myChart.hideLoading();
        this.myChart.setOption(this.options);
      }

      window.addEventListener("resize", this.debounce(this.resizeHandler, 200));
      this.myChart.resize();
    },
  },
  watch: {
    options: {
      handler() {
        if (!this.loading) {
          this.myChart.hideLoading();
          this.myChart.setOption(this.options, true);
          this.myChart.resize();
        }
      },
      deep: true,
    },
    loading(newVal) {
      if (newVal) {
        this.myChart.showLoading();
      } else {
        this.myChart.hideLoading();
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener(
      "resize",
      this.debounce(this.resizeHandler, 200)
    );
    if (this.myChart) {
      this.myChart.dispose();
    }
  },
};
</script>

<style scoped lang="scss">
.chart {
  border: calc(var(--border) * .025rem) solid #ebeef5;
  border-radius: .1rem;
  width: 100%;
  height: 100%;
  background: #ffffff;
  padding: 0.4rem;
}
</style>
